<template>
  <div class="page-container">
    <div class="header-section" v-if="diagnosis.strengths.length || diagnosis.issues.length">
      <h2 class="page-title">本次面试报告</h2>
      <el-button @click="saveToPDF" :loading="pdfLoading" class="yellow-btn">
        <i class="el-icon-download"></i> 保存分析报告
      </el-button>
    </div>

    <div v-if="!diagnosis.strengths.length && !diagnosis.issues.length" class="loading-card">
      <div class="loading-content">
        <img src="@/assets/images/loading.png" alt="loading" class="loading-image" />
        <p class="loading-text">面试报告生成中，请稍后，大约等候 1-2 分钟。</p>
      </div>
    </div>

    <div class="content-wrapper">
      <!-- 输入区域 -->
      <!-- <div class="input-section card">
        <el-input
          type="textarea"
          v-model="chatLog"
          :rows="5"
          resize="none"
        ></el-input>
      </div> -->

      <!--智能逐题分析-->
      <div class="qa-analysis-section" v-if="qaAnalysis.length">
        <h3 class="section-title">智能逐题分析</h3>
        <div class="qa-block" v-for="(item, idx) in qaAnalysis" :key="idx">
          <div class="qa-section qa-question">
            <div class="qa-title">面试官：</div>
            <div class="qa-content">{{ item.question }}</div>
          </div>
          <div class="qa-section qa-ai-answer">
            <div class="qa-title">智能回答：</div>
            <div class="qa-content">{{ item.aiAnswer }}</div>
          </div>
          <div class="qa-section qa-user-answer">
            <div class="qa-title">你的回答：</div>
            <div class="qa-content">{{ item.userAnswer }}</div>
          </div>
          <div class="qa-section qa-advantage">
            <div class="qa-title">优势分析：</div>
            <div class="qa-content">{{ item.advantage }}</div>
          </div>
          <div class="qa-section qa-disadvantage">
            <div class="qa-title">劣势分析：</div>
            <div class="qa-content">{{ item.disadvantage }}</div>
          </div>
          <div class="qa-section qa-suggestion">
            <div class="qa-title">改进建议：</div>
            <div class="qa-content">{{ item.suggestion }}</div>
          </div>
        </div>
      </div>



      <!-- 结果展示区域 -->
      <div class="result-section" v-if="diagnosis.strengths.length || diagnosis.issues.length">
        <!-- 雷达图区域 -->
        <div class="chart-area card">
          <h3 class="section-title"><i class="el-icon-caret-right" style="color: rgb(255, 180, 54);"></i>能力评估雷达图</h3>
          <div class="chart-grid">
            <div ref="radarChart1" class="chart-item"></div>
            <div ref="radarChart2" class="chart-item"></div>
          </div>
        </div>

        <!-- 视频语音分析区域 -->
        <div class="chart-area card">
          <h3 class="section-title"><i class="el-icon-caret-right" style="color: rgb(255, 180, 54);"></i>视频语音分析</h3>
          <div class="chart-grid">
            <div ref="videoEmotionChart" class="chart-item"></div>
            <div ref="voiceScoreChart" class="chart-item"></div>
            <p class="analysis-content">{{ videoAnalysisresult }}</p>
            <p class="analysis-content">{{ voiceAnalysisresult }}</p>
          </div>
        </div>

        <!-- 趋势分析区域 -->
        <div class="chart-area card">
          <h3 class="section-title"><i class="el-icon-caret-right" style="color: rgb(255, 180, 54);"></i>能力变化趋势</h3>
          <div class="trend-chart-grid">
            <div ref="generalTrendChart" class="trend-chart-item"></div>
            <div ref="professionalTrendChart" class="trend-chart-item"></div>
          </div>
        </div>

        <h3 class="section-title"><i class="el-icon-caret-right" style="color: rgb(255, 180, 54);"></i>优缺点分析</h3>
        <!-- 诊断结果区域 -->
        <div class="diagnosis-section card">

          <div class="diagnosis-column">
            <h3 class="advantage-title">
              <i class="el-icon-success"></i> 个人优势
            </h3>
            <ul class="advantage-list">
              <li v-for="(item, idx) in diagnosis.strengths" :key="idx">{{ item }}</li>
            </ul>
          </div>

          <div class="diagnosis-column">
            <h3 class="issue-title">
              <i class="el-icon-warning"></i> 关键问题与建议
            </h3>
            <ul class="issue-list">
              <li v-for="(item, idx) in diagnosis.issues" :key="idx">
                <p class="issue-item"><strong>问题：</strong>{{ item.problem }}</p>
                <p class="suggestion-item"><strong>建议：</strong>{{ item.suggestion }}</p>
              </li>
            </ul>
          </div>
        </div>

        <!-- 综合评估区域 -->
        <div class="assessment-section card">
          <div class="assessment-header">
            <div class="job-fit-section">
              <h3><i class="el-icon-caret-right" style="color: rgb(255, 180, 54);"></i>岗位匹配度</h3><br>
              <div class="fit-score">
                <div class="score-value">{{ jobFit.score }}</div>
                <div class="score-level">{{ jobFit.level }}</div>
              </div>
            </div>
            <div class="position-info">
              <strong>应聘岗位：</strong>{{ appliedPosition }}
            </div>
          </div>

          <div class="evaluation-content">
            <h4>综合评价</h4>
            <p class="evaluation-text">{{ overallEvaluation }}</p>
          </div>
        </div>

        <!-- 详细评估表格 -->
        <div class="table-section card">
          <h3 class="section-title"><i class="el-icon-caret-right" style="color: rgb(255, 180, 54);"></i>能力维度评估</h3>
          <el-table :data="assessmentItems" style="width: 100%;font-size: 14px;">
            <el-table-column prop="dimension" label="能力维度" width="180"></el-table-column>
            <el-table-column prop="requirement" label="要求说明"></el-table-column>
            <el-table-column prop="result" label="评估结果" width="120">
              <template #default="{ row }">
                {{ row.result }}/100
              </template>
            </el-table-column>
            <el-table-column prop="matchLevel" label="匹配度" width="120">
              <template #default="{ row }">
                <el-tag>
                  {{ row.matchLevel }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 学习资源推荐 -->
        <div class="resource-section card">
          <div class="resource-header">
            <h3 class="section-title"><i class="el-icon-caret-right" style="color: rgb(255, 180, 54);"></i>学习资源推荐</h3>
            <p class="suggestion-text">{{ suggestions }}</p>
          </div>
          <ul class="resource-list">
            <li v-for="(resource, index) in learningResources" :key="index" class="resource-item">
              <div class="resource-info">
                <span class="resource-name">{{ resource.name }}</span>
                <span class="resource-type">{{ resource.url }}</span>
              </div>
              <div class="resource-actions">
                <el-button size="mini" @click="openResource(resource.url)" type="text">
                  查看资源
                </el-button>
                <el-button size="mini" :type="collectedStatus[index] ? 'success' : 'primary'"
                  @click="collectResource(resource, index)" :disabled="collectedStatus[index]">
                  {{ collectedStatus[index] ? '已收藏' : '收藏' }}
                </el-button>
              </div>
            </li>
          </ul>
        </div>

        <!-- 趋势分析 -->
        <div class="analysis-section card">
          <h3 class="section-title"><i class="el-icon-caret-right" style="color: rgb(255, 180, 54);"></i>能力变化趋势分析</h3>
          <p class="analysis-content">{{ trendAnalysis }}</p>
        </div>

      <el-button @click="returnHome" :loading="pdfLoading" class="yellow-btn">
        <i class="ym-custom ym-custom-keyboard-return"></i> 返回主页
      </el-button>

      </div>
    </div>
  </div>
</template>

<script>
import CryptoJS from "crypto-js";
import * as echarts from "echarts";
import request from '@/utils/request'
import { getComprehensiveAbilityList, getProfessionalAbilityList } from '@/api/example/ability'
import { mapGetters } from 'vuex';
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
import OSS from 'ali-oss'

export default {
  data() {
    return {
      chatLog: "",
      responseStatus: "init",
      list: [],
      appId: 'e9f15e7b',
      apiSecret: 'YTk4MzhhOGY5MDNjNWI2ZjAzYjEwMWVi',
      apiKey: '8f4950aa42fdca8eac189b3edb74da82',
      wsHost: "spark-api.xf-yun.com",

      ttsWS: null,
      totalRes: "",
      diagnosis: { strengths: [], issues: [] },
      abilityData: { general: {}, professional: {} },
      showCharts: false,
      jobFit: {
        score: 0,
        level: ''
      },
      query: {
        inid: undefined,
        date: undefined,
        record: undefined,
        vedio: undefined,
        voice: undefined,
      },
      appliedPosition: '',
      overallEvaluation: '',
      assessmentItems: [],
      trendLabels: [], // 时间标签
      generalTrendData: [], // 趋势数据数组 { name, data }
      professionalTrendData: [],
      trendAnalysis: '',
      suggestions: '',
      learningResources: '',
      collectedStatus: {}, // 记录资源收藏状态 {index: boolean}
      selectedHistoryId: null,
      selectedHistoryContent: '',
      videoAnalysis: [],
      voiceAnalysis: [],
      autoLoading: false,
      pdfLoading: false,
      ossConfig: {
        region: 'oss-cn-wuhan-lr',
        accessKeyId: 'LTAI5tE1sjS9v6rVPid3HXzr',
        accessKeySecret: 'd3dCLmg0CBQgMX5fbSjZc6qMPWJcMj',
        bucket: 'mangopdf',
      },
      qaAnalysis: [], // 逐题分析结果
      qaLoading: false, // 分析加载状态
    };
  },
  computed: {
    currentUser() {
      return this.$store.state.user || {};
    },
    // 添加获取历史记录的 getter
    ...mapGetters('history', ['getAllInterviewHistories']),

    // 计算属性获取历史记录
    interviewHistories() {
      return this.getAllInterviewHistories || [];
    },
  },
  mounted() {
    this.fetchComprehensiveAbility();
    this.fetchProfessionalAbility();
    this.autoAnalyze();
  },
  methods: {
    async analyzeQA() {
      if (!this.chatLog.trim()) {
        this.$message.warning('请先输入聊天记录');
        return;
      }
      this.qaLoading = true;
      try {
        // 解析聊天记录
        const qaList = [];
        const regex = /面试官:\s*([\s\S]*?)\n候选人:\s*([\s\S]*?)(?=\n面试官:|\n*$)/g;
        let match;
        while ((match = regex.exec(this.chatLog)) !== null) {
          qaList.push({
            question: match[1].trim(),
            userAnswer: match[2].trim(),
          });
        }
        // 构造AI提示词
        const prompt = `
            请对下面的面试问答进行逐题智能分析。对于每一组“面试官问题+候选人回答”，请输出：
            1. 针对该问题的标准智能回答
            2. 对候选人回答的优势分析
            3. 对候选人回答的劣势分析
            4. 针对该回答的改进建议
            请严格输出如下JSON数组格式：
            [
              {
                "question": "面试官问题",
                "aiAnswer": "智能回答",
                "userAnswer": "候选人回答",
                "advantage": "优势分析",
                "disadvantage": "劣势分析",
                "suggestion": "改进建议"
              },
              ...
            ]
            面试问答内容如下：
            ${JSON.stringify(qaList, null, 2)}
            请只输出JSON数组，不要有任何多余内容。
                    `;
        // 获取WebSocket地址
        const url = await this.getWebsocketUrl();
        const ws = new WebSocket(url);
        let res = '';
        ws.onopen = () => {
          const params = {
            header: {
              app_id: this.appId,
              uid: "user-unique-id",
            },
            parameter: {
              chat: {
                domain: "generalv3.5",
                temperature: 0.5,
                max_tokens: 2048,
              },
            },
            payload: {
              message: {
                text: [{ role: "user", content: prompt }],
              },
            },
          };
          ws.send(JSON.stringify(params));
        };
        ws.onmessage = (e) => {
          try {
            const json = JSON.parse(e.data);
            if (
              json.payload &&
              json.payload.choices &&
              json.payload.choices.text &&
              json.payload.choices.text[0] &&
              json.payload.choices.text[0].content
            ) {
              res += json.payload.choices.text[0].content;
            }
            if (json.header.status === 2) {
              ws.close();
              // 清理AI返回内容
              let clean = res
                .replace(/^```(json)?/g, "")
                .replace(/```$/g, "")
                .trim();
              try {
                this.qaAnalysis = JSON.parse(clean);
              } catch (e) {
                this.qaAnalysis = [];
                this.$message.error('AI返回格式解析失败');
              }
              this.qaLoading = false;
            }
          } catch (e) {
            this.qaLoading = false;
            this.$message.error('AI逐题分析失败');
          }
        };
        ws.onerror = () => {
          this.qaLoading = false;
          this.$message.error('AI逐题分析请求失败');
        };
      } catch (e) {
        this.qaLoading = false;
        this.$message.error('AI逐题分析异常');
      }
    },
    // 自动分析历史记录
    autoAnalyze() {
      this.autoLoading = true;
      this.getRecord().then(() => {
        this.$nextTick(() => {
          if (this.chatLog.trim()) {
            this.generateAnalysis();
          }
          this.autoLoading = false;
        });
      }).catch(() => {
        this.autoLoading = false;
      });
    },
    // 加载选中的历史记录
    loadHistory() {
      if (!this.selectedHistoryId) return;

      const history = this.interviewHistories.find(
        h => h.id === this.selectedHistoryId
      );

      if (history) {
        // 将历史记录中的聊天内容转换为字符串
        this.selectedHistoryContent = history.records
          .map(record => `${record.role}: ${record.content}`)
          .join('\n');

        // 自动填充到聊天记录输入框
        this.chatLog = this.selectedHistoryContent;
      }
    },
    returnHome(){
        this.$router.push({ path: '/homePage' });
    },
    getWebsocketUrl() {
      return new Promise((resolve, reject) => {
        try {
          const host = this.wsHost;
          const path = "/v3.5/chat";
          const date = new Date().toUTCString();
          const algorithm = "hmac-sha256";
          const headers = "host date request-line";
          const signatureOrigin = `host: ${host}\ndate: ${date}\nGET ${path} HTTP/1.1`;
          const signatureSha = CryptoJS.HmacSHA256(signatureOrigin, this.apiSecret);
          const signature = CryptoJS.enc.Base64.stringify(signatureSha);
          const authorizationOrigin = `api_key="${this.apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
          const authorization = btoa(authorizationOrigin);
          const url = `wss://${host}${path}?authorization=${authorization}&date=${date}&host=${host}`;
          resolve(url);
        } catch (e) {
          reject(e);
        }
      });
    },

    generateAnalysis() {
      if (this.selectedHistoryContent) {
        this.chatLog = this.selectedHistoryContent;
      }
      if (this.responseStatus === "loading") return;

      this.responseStatus = "loading";
      this.totalRes = "";
      this.diagnosis = { strengths: [], issues: [] };
      this.abilityData = { general: {}, professional: {} };
      this.showCharts = false;

      this.getWebsocketUrl()
        .then((url) => {
          if ("WebSocket" in window) {
            this.ttsWS = new WebSocket(url);
          } else {
            alert("浏览器不支持WebSocket");
            this.responseStatus = "error";
            return;
          }

          this.ttsWS.onopen = () => {
            this.sendMessage();
          };

          this.ttsWS.onmessage = (e) => {
            this.handleMessage(e.data);
          };

          this.ttsWS.onerror = (e) => {
            console.error("WebSocket错误:", e);
            alert("WebSocket连接错误，请查看控制台");
            this.responseStatus = "error";
          };

          this.ttsWS.onclose = () => {
            this.responseStatus = "init";
          };
        })
        .catch((err) => {
          console.error("获取WebSocket地址失败:", err);
          alert("生成失败，请重试");
          this.responseStatus = "error";
        });
    },

    sendMessage() {
      // 让模型返回纯JSON，不带代码块
      const prompt = `请根据以下聊天记录,以及音频和表情数据,其中音频数据的分数表示语气平和的分数,学习资源推荐最好是中文书籍,严格按照下面的 JSON 格式输出,学习资源推荐即便是书籍，也要在书名号外面带上引号，保证json格式。包含综合能力评估、专业能力评估和问题诊断等,各种能力的分数实行百分制,示例如下：
      {
        "综合能力评估": {"语言表达能力": 0, "逻辑思维能力": 0, "创新能力": 0, "专业知识水平": 0, "应变抗压能力": 0, "技能匹配度": 0},
        "专业能力评估": {"编程与工程": 0, "基础知识": 0, "前沿知识与理论理解": 0, "项目经验": 0, "解决问题能力": 0, "合作和沟通能力": 0},
        "问题诊断": {
          "strengths": ["优势1", "优势2"],
          "issues": [
            {"problem":"问题1", "suggestion":"建议1"},
            {"problem":"问题2", "suggestion":"建议2"}
          ]
        }     //每项内容尽可能详细(不少于200字)
        "岗位匹配度": {"score": 0, "level": ""},
        "应聘岗位": "",
        "综合评价": "",
        "面试表现能力匹配评估": [
          {"dimension": "", "requirement": "", "result": 0, "matchLevel": ""}
        ],
        "建议加强项": "",
        "学习资源推荐": [
          {
            "name": "资源名称",
            "url": "资源链接",
            "type": "资源类型(书籍/视频/文章等)"
          },
          {
            "name": "资源名称2",
            "url": "资源链接2",
            "type": "资源类型2"
          }
        ],
        "音频分析":"音频分析结果",
        "视频分析":"视频分析结果"
      }
        严格按照上面的 JSON 格式输出,学习资源推荐即便是书籍，也要在书名号外面带上引号，保证json格式。
      聊天记录：
      ${this.chatLog}
      ${this.videoAnalysis.length ? `视频分析：${JSON.stringify(this.videoAnalysis)}` : ''}
      ${this.voiceAnalysis.length ? `语音分析：${JSON.stringify(this.voiceAnalysis)}` : ''}
      请**不要**带任何 Markdown 代码块，仅输出纯 JSON。`;

      const params = {
        header: {
          app_id: this.appId,
          uid: "user-unique-id",
        },
        parameter: {
          chat: {
            domain: "generalv3.5",
            temperature: 0.7,
            max_tokens: 2048,
          },
        },
        payload: {
          message: {
            text: [{ role: "user", content: prompt }],
          },
        },
      };

      this.ttsWS.send(JSON.stringify(params));
    },

    handleMessage(msg) {
      try {
        const json = JSON.parse(msg);
        // 检查返回code
        if (json.header.code !== 0) {
          alert("错误: " + json.header.code + " - " + json.header.message);
          this.responseStatus = "error";
          this.ttsWS.close();
          return;
        }

        if (
          json.payload &&
          json.payload.choices &&
          json.payload.choices.text &&
          json.payload.choices.text[0] &&
          json.payload.choices.text[0].content
        ) {
          const content = json.payload.choices.text[0].content;
          this.totalRes += content;

          if (json.header.status === 2) {
            // 结束，处理结果
            this.processResult(this.totalRes);
            this.ttsWS.close();
            this.responseStatus = "init";
          }
        }
      } catch (e) {
        console.error("解析消息失败:", e);
        this.responseStatus = "error";
      }
    },
    fetchComprehensiveAbility() {
      getComprehensiveAbilityList({
        currentPage: 1,
        pageSize: 5 // 获取最近5次记录
      }).then(res => {
        this.comprehensiveHistory = this.transformAbilityData(res.data.list || [], [
          "语言表达能力", "逻辑思维能力", "创新能力",
          "专业知识水平", "应变抗压能力", "技能匹配度"
        ]);
      });
    },

    // 获取专业能力历史数据
    fetchProfessionalAbility() {
      getProfessionalAbilityList({
        currentPage: 1,
        pageSize: 5 // 获取最近5次记录
      }).then(res => {
        this.professionalHistory = this.transformAbilityData(res.data.list || [], [
          "编程与工程", "基础知识", "前沿知识与理论理解",
          "项目经验", "解决问题能力", "合作和沟通能力"
        ]);
      });
    },

    // 转换API数据为图表可用的格式
    transformAbilityData(list, abilityNames) {
      const timeSet = new Set();
      const abilityMap = {};

      // 初始化能力映射
      abilityNames.forEach(name => { abilityMap[name] = [] });

      // 处理数据
      list.forEach(item => {
        timeSet.add(item.time);
        if (abilityMap[item.type]) {
          abilityMap[item.type].push({
            time: item.time,
            score: Number(item.score) || 0
          });
        }
      });

      // 生成时间标签
      const timeList = Array.from(timeSet).sort((a, b) => new Date(a) - new Date(b));
      this.trendLabels = timeList.map((_, i) => `第${i + 1}次`);

      // 生成图表系列数据
      return abilityNames.map(name => {
        const data = timeList.map(time => {
          const entry = abilityMap[name].find(e => e.time === time);
          return entry ? entry.score : 0;
        });
        return {
          name,
          type: 'line',
          data,
          smooth: true
        };
      });
    },

    processResult(content) {
      try {
        let cleanContent = content
          // 移除JSON代码块标记
          .replace(/^```(json)?/g, "")
          .replace(/```$/g, "")
          // 移除所有控制字符（包括换行符、制表符等）
          .replace(/[\u0000-\u001F\u007F-\u009F]/g, "")
          // 处理转义字符
          .replace(/\\n/g, '\n')
          .replace(/\\'/g, "'")
          .replace(/\\"/g, '"')
          // 移除前后空白
          .trim();

        // 尝试解析
        const result = JSON.parse(cleanContent);

        this.abilityData.general = result["综合能力评估"] || {};
        this.abilityData.professional = result["专业能力评估"] || {};
        this.diagnosis = result["问题诊断"] || { strengths: [], issues: [] };
        this.jobFit.score = result['岗位匹配度'].score || 0;
        this.jobFit.level = result['岗位匹配度'].level || '';
        this.appliedPosition = result['应聘岗位'] || '';
        this.overallEvaluation = result['综合评价'] || '';
        this.assessmentItems = result['面试表现能力匹配评估'] || [];
        this.suggestions = result['建议加强项'] || '';
        this.learningResources = result['学习资源推荐'] || [];
        // 初始化收藏状态
        this.learningResources.forEach((_, index) => {
          this.$set(this.collectedStatus, index, false);
        });
        this.videoAnalysisresult = result['视频分析'] || [];
        this.voiceAnalysisresult = result['音频分析'] || [];
        this.showCharts = true;
        this.$nextTick(() => {
          this.renderCharts(); // 雷达图
          this.renderTrendLineChart(); // 折线图
          this.renderVideoEmotionChart(); // 新增视频情绪图表
          this.renderVoiceScoreChart(); // 新增语音分数图表
        });
        this.saveComprehensiveAbility();
        this.saveProfessionalAbility();
      } catch (e) {
        alert("返回结果格式错误，无法解析JSON");
        console.error("JSON解析失败:", e, "原始内容:", content);
        this.responseStatus = "error";
      }
    },
    renderCharts() {
      if (!this.showCharts) return;

      // ======== 综合能力雷达图 ========
      const radar1 = echarts.init(this.$refs.radarChart1);
      radar1.setOption({
        tooltip: {
          show: true,
          backgroundColor: '#fff',
          borderColor: '#eee',
          textStyle: { color: '#444' }
        },
        legend: {
          data: ['综合能力'],
          top: 20,
          right: 10,
          icon: 'circle',
          itemWidth: 10,
          itemHeight: 10,
          textStyle: { color: '#444', fontWeight: 400, fontSize: 13 }
        },
        radar: {
          indicator: Object.keys(this.abilityData.general).map((k) => ({
            name: k,
            max: 100
          })),
          splitNumber: 4,
          radius: '70%',
          axisName: {
            color: '#444',
            fontWeight: 400,
            fontSize: 13,
            padding: [2, 4]
          },
          splitArea: {
            areaStyle: {
              color: ['#faf8f2', '#f5f5f5', '#fff']
            }
          },
          splitLine: {
            lineStyle: {
              color: '#e0e0e0',
              width: 1
            }
          },
          axisLine: {
            lineStyle: {
              color: '#e0e0e0',
              width: 1
            }
          }
        },
        series: [
          {
            name: '综合能力',
            type: 'radar',
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
              color: '#ff9800',
              width: 2
            },
            itemStyle: {
              color: '#ff9800',
              borderColor: '#fff',
              borderWidth: 1
            },
            areaStyle: {
              color: 'rgba(255, 152, 0, 0.08)' // 绿色淡填充
            },
            data: [
              {
                value: Object.values(this.abilityData.general),
                name: '综合能力'
              }
            ]
          }
        ]
      });

      // ======== 专业能力雷达图 ========
      const radar2 = echarts.init(this.$refs.radarChart2);
      radar2.setOption({
        tooltip: {
          show: true,
          backgroundColor: '#fff',
          borderColor: '#eee',
          textStyle: { color: '#444' }
        },
        legend: {
          data: ['专业能力'],
          top: 20,
          right: 10,
          icon: 'circle',
          itemWidth: 10,
          itemHeight: 10,
          textStyle: { color: '#444', fontWeight: 400, fontSize: 13 }
        },
        radar: {
          indicator: Object.keys(this.abilityData.professional).map((k) => ({
            name: k,
            max: 100
          })),
          splitNumber: 4,
          radius: '70%',
          axisName: {
            color: '#444',
            fontWeight: 400,
            fontSize: 13,
            padding: [2, 4]
          },
          splitArea: {
            areaStyle: {
              color: ['#faf8f2', '#f5f5f5', '#fff']
            }
          },
          splitLine: {
            lineStyle: {
              color: '#e0e0e0',
              width: 1
            }
          },
          axisLine: {
            lineStyle: {
              color: '#e0e0e0',
              width: 1
            }
          }
        },
        series: [
          {
            name: '专业能力',
            type: 'radar',
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
              color: '#ff9800', // 橙色
              width: 2
            },
            itemStyle: {
              color: '#ff9800',
              borderColor: '#fff',
              borderWidth: 1
            },
            areaStyle: {
              color: 'rgba(255, 152, 0, 0.08)' // 橙色淡填充
            },
            data: [
              {
                value: Object.values(this.abilityData.professional),
                name: '专业能力'
              }
            ]
          }
        ]
      });
    },
    // 渲染趋势折线图
    renderTrendLineChart() {
      const colorList = [
        '#f19584', '#fea386', '#29c6cd', '#c5ecbe',
        '#dea6d5', '#8fbaf3'
      ];
      const newTrendLabels = [...this.trendLabels, "本次分析"];

      // ====== 综合能力趋势图 ======
      const generalChart = echarts.init(this.$refs.generalTrendChart);
      const generalSeries = this.comprehensiveHistory.map((item, idx) => {
        const currentValue = this.abilityData.general[item.name] || 0;
        const color = colorList[idx % colorList.length];
        return {
          name: item.name,
          type: 'line',
          data: [...item.data, currentValue],
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: {
            color,
            width: 2
          },
          itemStyle: {
            color,
            borderColor: '#fff',
            borderWidth: 1
          },
          // areaStyle: {
          //   color: color + '22' // 加一点填充
          // }
        };
      });

      generalChart.setOption({
        tooltip: {
          trigger: 'axis',
          backgroundColor: '#fff',
          borderColor: '#eee',
          textStyle: { color: '#444' }
        },
        legend: {
          data: this.comprehensiveHistory.map(item => item.name),
          top: '10px',
          right: '10px',
          icon: 'circle',
          itemWidth: 10,
          itemHeight: 10,
          textStyle: {
            color: '#888',
            fontWeight: 400,
            fontSize: 13
          }
        },
        grid: {
          left: '36px',
          right: '36px',
          top: '70px',
          bottom: '32px'
        },
        xAxis: {
          type: 'category',
          data: newTrendLabels,
          axisLine: { lineStyle: { color: '#e0e0e0', width: 1 } },
          axisLabel: {
            color: '#888',
            fontWeight: 400,
            fontSize: 13,
            margin: 8
          },
          splitLine: { show: false }
        },
        yAxis: {
          type: 'value',
          max: 100,
          axisLine: { lineStyle: { color: '#e0e0e0', width: 1 } },
          axisLabel: {
            color: '#888',
            fontWeight: 400,
            fontSize: 13
          },
          splitLine: { lineStyle: { color: '#f5f5f5', width: 1 } }
        },
        series: generalSeries
      });

      // ====== 专业能力趋势图 ======
      const professionalChart = echarts.init(this.$refs.professionalTrendChart);
      const professionalSeries = this.professionalHistory.map((item, idx) => {
        const currentValue = this.abilityData.professional[item.name] || 0;
        const color = colorList[idx % colorList.length];
        return {
          name: item.name,
          type: 'line',
          data: [...item.data, currentValue],
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: {
            color,
            width: 2
          },
          itemStyle: {
            color,
            borderColor: '#fff',
            borderWidth: 1
          },
          // areaStyle: {
          //   color: color + '22'
          // }
        };
      });

      professionalChart.setOption({
        tooltip: {
          trigger: 'axis',
          backgroundColor: '#fff',
          borderColor: '#eee',
          textStyle: { color: '#444' }
        },
        legend: {
          data: this.professionalHistory.map(item => item.name),
          top: '10px',
          right: '10px',
          icon: 'circle',
          itemWidth: 10,
          itemHeight: 10,
          textStyle: {
            color: '#888',
            fontWeight: 400,
            fontSize: 13
          }
        },
        grid: {
          left: '36px',
          right: '36px',
          top: '70px',
          bottom: '32px'
        },
        xAxis: {
          type: 'category',
          data: newTrendLabels,
          axisLine: { lineStyle: { color: '#e0e0e0', width: 1 } },
          axisLabel: {
            color: '#888',
            fontWeight: 400,
            fontSize: 13,
            margin: 8
          },
          splitLine: { show: false }
        },
        yAxis: {
          type: 'value',
          max: 100,
          axisLine: { lineStyle: { color: '#e0e0e0', width: 1 } },
          axisLabel: {
            color: '#888',
            fontWeight: 400,
            fontSize: 13
          },
          splitLine: { lineStyle: { color: '#f5f5f5', width: 1 } }
        },
        series: professionalSeries
      });

      this.analyzeTrendAfterChartRender();
    },

    analyzeTrendAfterChartRender() {
      // 构造趋势分析提示
      const prompt = `
      请根据以下能力数据变化趋势进行分析：

      **综合能力历史数据**:
      ${JSON.stringify(this.comprehensiveHistory, null, 2)}

      **专业能力历史数据**:
      ${JSON.stringify(this.professionalHistory, null, 2)}

      **本次分析数据**:
      综合能力: ${JSON.stringify(this.abilityData.general)}
      专业能力: ${JSON.stringify(this.abilityData.professional)}

      请分析能力变化趋势，指出：
      1. 进步最明显的领域
      2. 需要特别关注的领域
      3. 整体趋势评估
      输出要求：
      - 直接输出纯文本分析报告，不要包含任何格式标记
      - 不要使用Markdown、JSON或任何代码块
      - 不要添加标题或列表符号
      - 输出简洁的分析报告（不超过200字）
      `;

      // 调用AI分析
      this.getWebsocketUrl().then(url => {
        const ws = new WebSocket(url);

        ws.onopen = () => {
          const params = {
            header: {
              app_id: this.appId,
              uid: "user-unique-id",
            },
            parameter: {
              chat: {
                domain: "generalv3.5",
                temperature: 0.5,
                max_tokens: 300,
              },
            },
            payload: {
              message: {
                text: [{ role: "user", content: prompt }],
              },
            },
          };
          ws.send(JSON.stringify(params));
        };

        let trendRes = "";
        ws.onmessage = (e) => {
          try {
            const json = JSON.parse(e.data);
            if (json.payload &&
              json.payload.choices &&
              json.payload.choices.text &&
              json.payload.choices.text[0] &&
              json.payload.choices.text[0].content) {
              trendRes += json.payload.choices.text[0].content;
            }

            if (json.header.status === 2) {
              ws.close();
              // 清理可能的代码块标记
              this.trendAnalysis = trendRes
                .replace(/^```(json)?\s*/, "")  // 移除开头的代码块标记
                .replace(/\s*```$/, "")         // 移除结尾的代码块标记
                .replace(/^\s*[\{\[]\s*/, "")   // 移除开头的JSON结构标记
                .replace(/\s*[\}\]]\s*$/, "")   // 移除结尾的JSON结构标记
                .replace(/\*\*分析报告：\*\*\s*/, "") // 移除多余的标题标记
                .replace(/^\s*[1-3]\.\s+/g, "") // 移除数字列表标记
                .replace(/\*\*/g, "")            // 移除所有星号标记
                .trim();
            }
          } catch (e) {
            console.error("趋势分析消息解析失败:", e);
          }
        };

        ws.onerror = (e) => {
          console.error("趋势分析WebSocket错误:", e);
          this.trendAnalysis = "趋势分析请求失败，请重试";
        };
      }).catch(err => {
        console.error("获取趋势分析WebSocket地址失败:", err);
        this.trendAnalysis = "无法连接趋势分析服务";
      });
    },
    // 新增打开资源方法
    openResource(url) {
      window.open(url, '_blank');
    },

    // 修改收藏方法
    collectResource(resource, index) {
      const collectData = {
        name: resource.name,
        type: resource.type || '08ba3e0aa0694b77bc06f91000ee59ad',
        url: resource.url,
        userid: localStorage.getItem("id") || "system",
        todate: new Date().toISOString()
      };

      request({
        url: '/api/example/Whu_learningcollection',
        method: 'post',
        data: collectData
      }).then(() => {
        this.$set(this.collectedStatus, index, true);
        this.$message.success('收藏成功');
      }).catch(error => {
        console.error('收藏失败:', error);
        this.$message.error('收藏失败');
      });
    },
    // 获取历史记录
    getRecord() {
      return new Promise((resolve, reject) => {
        this.query.inid = this.query.inid || localStorage.getItem("id") || "system";
        let _query = { ...this.query };

        request({
          url: `/api/example/Whu_record/getList`,
          method: 'post',
          data: _query
        }).then(res => {
          var _list = [];
          for (let i = 0; i < res.data.list.length; i++) {
            let _data = res.data.list[i];
            _list.push(_data);

            // 自动设置最新记录为默认分析内容
            if (i === 0) {
              try {
                // 解析历史记录
                const records = JSON.parse(_data.record);

                // 将聊天记录转换为对话文本格式
                const chatLog = records.map(item =>
                  `面试官: ${item.question}\n候选人: ${item.answer}`
                ).join('\n\n');

                // 自动填充到聊天记录输入框
                this.chatLog = chatLog;

                // 自动填充视频和语音分析数据
                this.videoAnalysis = JSON.parse(_data.vedio);
                this.voiceAnalysis = JSON.parse(_data.voice);
                console.log('视频分析结果', this.videoAnalysis);
                console.log('语音分析结果', this.voiceAnalysis);

                console.log('已自动设置默认分析记录');
              } catch (e) {
                console.error('解析历史记录失败:', e);
              }
            }
          }
          this.list = _list;
          console.log('历史记录', this.list);
          console.log('历史记录加载完成');
          resolve(res); // 解析完成
        }).catch(error => {
          console.error('获取历史记录失败:', error);
          reject(error);
        });
      });
    },
    // 渲染视频情绪分析折线图
    renderVideoEmotionChart() {
      if (!this.videoAnalysis.length) return;

      const chart = echarts.init(this.$refs.videoEmotionChart);
      const timeData = this.videoAnalysis.map(item => item.time);
      const emotionData = this.videoAnalysis.map(item => {
        // 将情绪转换为数值用于图表展示
        const emotions = {
          '开心': 100,
          '中性': 50,
          '悲伤': 0,
          '恐惧': -25,
          '生气': -50,
          '未知': 25
        };
        return emotions[item.emotion] || 25;
      });

      chart.setOption({
        title: { text: '视频情绪变化趋势', left: 'center' },
        tooltip: {
          formatter: params => {
            const index = params.dataIndex;
            return `时间: ${this.videoAnalysis[index].time}<br/>
                    情绪: ${this.videoAnalysis[index].emotion}`;
          }
        },
        xAxis: {
          type: 'category',
          data: timeData,
          name: '时间'
        },
        yAxis: {
          type: 'value',
          name: '情绪值',
          axisLabel: {
            formatter: value => {
              if (value === 100) return '开心';
              if (value === 50) return '中性';
              if (value === 0) return '悲伤';
              if (value === -50) return '愤怒';
              if (value === -25) return '恐惧';
              return '未知';
            }
          }
        },
        series: [{
          data: emotionData,
          type: 'line',
          smooth: true,
          lineStyle: {
            color: '#5470C6'
          },
          itemStyle: {
            color: '#5470C6'
          }
        }]
      });
    },

    // 渲染语音分数分析折线图
    renderVoiceScoreChart() {
      if (!this.voiceAnalysis.length) return;

      const chart = echarts.init(this.$refs.voiceScoreChart);
      const timeData = this.voiceAnalysis.map(item => `${item.time}秒`);
      const scoreData = this.voiceAnalysis.map(item => item.score);

      chart.setOption({
        title: { text: '语音分数变化趋势', left: 'center' },
        tooltip: {
          formatter: params => {
            const index = params.dataIndex;
            return `时间: ${this.voiceAnalysis[index].time}秒<br/>
                    分数: ${this.voiceAnalysis[index].score.toFixed(2)}`;
          }
        },
        xAxis: {
          type: 'category',
          data: timeData,
          name: '时间'
        },
        yAxis: {
          type: 'value',
          name: '分数',
          min: 0,
          max: 10
        },
        series: [{
          data: scoreData,
          type: 'line',
          smooth: true,
          lineStyle: {
            color: '#91CC75'
          },
          itemStyle: {
            color: '#91CC75'
          }
        }]
      });
    },
    async saveToPDF() {
      try {
        this.pdfLoading = true

        // 生成PDF
        const pdfBlob = await this.generatePDF();

        // 上传到OSS
        const pdfUrl = await this.uploadToOSS(pdfBlob);

        await this.saveAnalysisReport(pdfUrl);

        // 显示成功消息
        this.$message.success(`分析报告保存成功，URL: ${pdfUrl}`);



      } catch (error) {
        console.error('保存PDF失败:', error)
        this.$message.error('保存分析报告失败')
      } finally {
        this.pdfLoading = false
      }
    },
    async generatePDF() {
      try {
        const element = document.querySelector('.page-container');

        // 1. 确保所有图表已渲染
        await Promise.all([
          this.$nextTick(),
          new Promise(resolve => setTimeout(resolve, 500)) // 额外等待时间
        ]);

        // 2. 提高PDF生成质量
        const canvas = await html2canvas(element, {
          scale: 2,                  // 提高分辨率
          logging: false,
          useCORS: true,
          allowTaint: true,
          scrollY: -window.scrollY,  // 解决滚动位置问题
          windowWidth: document.documentElement.scrollWidth,
          windowHeight: document.documentElement.scrollHeight
        });

        // 3. 分页处理
        const pdf = new jsPDF('p', 'mm', 'a4');
        const imgData = canvas.toDataURL('image/png');
        const imgProps = pdf.getImageProperties(imgData);
        const pdfWidth = pdf.internal.pageSize.getWidth();
        const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;

        let heightLeft = pdfHeight;
        let position = 0;
        const pageHeight = pdf.internal.pageSize.getHeight() - 20; // 留边距

        while (heightLeft >= 0) {
          pdf.addImage(imgData, 'PNG', 0, position, pdfWidth, pdfHeight);
          heightLeft -= pageHeight;
          position -= pageHeight;

          if (heightLeft > 0) {
            pdf.addPage();
          }
        }

        return pdf.output('blob');
      } catch (error) {
        console.error('生成PDF失败:', error);
        throw error;
      }
    },
    async uploadToOSS(blob) {
      const client = new OSS(this.ossConfig)

      // 生成唯一文件名
      const fileName = `interview-reports/${this.currentUser.id || 'anonymous'}/${Date.now()}.pdf`

      const result = await client.put(fileName, blob, {
        headers: {
          'Content-Type': 'application/pdf',
          'Content-Disposition': `inline`
        }
      })
      console.log('上传成功:', result)
      return result.url
    },
    // 保存分析报告到后端
    async saveAnalysisReport(pdfUrl) {
      const reportData = {
        date: new Date().toISOString(),
        inid: localStorage.getItem("id") || 'system',
        analysis: pdfUrl  // 将PDF URL保存到analysis字段
      };

      try {
        const res = await request({
          url: '/api/example/Whu_report',
          method: 'post',
          data: reportData
        });
        return res;
      } catch (error) {
        console.error('保存报告失败:', error);
        throw error;
      }
    },
    // 保存综合能力数据
    saveComprehensiveAbility() {
      if (!this.abilityData.general) {
        this.$message.warning('没有可保存的综合能力数据');
        return;
      }

      // 遍历综合能力数据，每项能力单独保存
      const promises = Object.entries(this.abilityData.general).map(([type, score]) => {
        const formData = {
          score: score.toString(),
          type: type,
          inid: this.query.inid || localStorage.getItem("id") || "system",
          time: new Date().toISOString()
        };

        return request({
          url: '/api/example/Whu_comprehensiveability',
          method: 'post',
          data: formData
        });
      });

      Promise.all(promises)
        .then(() => {
          this.$message.success('综合能力数据保存成功');
          this.fetchComprehensiveAbility(); // 刷新历史数据
        })
        .catch(error => {
          console.error('保存综合能力失败:', error);
          this.$message.error('部分能力数据保存失败');
        });
    },
    saveProfessionalAbility() {
      if (!this.abilityData.professional) {
        this.$message.warning('没有可保存的专业能力数据');
        return;
      }

      // 遍历专业能力数据，每项能力单独保存
      const promises = Object.entries(this.abilityData.professional).map(([type, score]) => {
        const formData = {
          score: score.toString(),
          type: type,
          inid: this.query.inid || localStorage.getItem("id") || "system",
          time: new Date().toISOString()
        };

        return request({
          url: '/api/example/Whu_professionalability',
          method: 'post',
          data: formData
        });
      });

      Promise.all(promises)
        .then(() => {
          this.$message.success('专业能力数据保存成功');
          this.fetchProfessionalAbility(); // 刷新历史数据
        })
        .catch(error => {
          console.error('保存专业能力失败:', error);
          this.$message.error('部分专业数据保存失败');
        });
    },
  },

  beforeDestroy() {
    if (this.ttsWS && this.ttsWS.readyState !== WebSocket.CLOSED) {
      this.ttsWS.close();
    }
  },
  watch: {
    chatLog() {
      // 聊天记录变更时自动分析
      this.analyzeQA();
    }
  }
};
</script>

<style scoped>
/* 基础布局 */
.page-container {
  max-width: 1200px;
  margin-top: 30px;
  margin-bottom: 30px;
  margin-left: auto;
  margin-right: auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  border: #E6A23C 1px solid;
}

.loading-card {
  width: 1000px;
  height: 500px;
  margin-top: 50px;
  margin-left: auto;
  margin-right: auto;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #ffffff;
}

.loading-content {
  text-align: center;
}

.loading-image {
  width: 300px;
  height: 250px;
  margin-bottom: 16px;
}

.loading-text {
  font-size: 18px;
  color: #613e04;
  font-weight: 600;
  line-height: 1.4;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.yellow-btn {
  background-color: #faf8ee;
  /* 按钮默认背景色：黄色 */
  border-color: #ffdd00;
  color: #322100;
  font-size: medium;
  font-weight: 500;
}

.yellow-btn:hover,
.yellow-btn:focus {
  background-color: #f7d25c;
  /* hover 或 focus 时变浅黄色 */
  border-color: #eebb14;
  color: #fff;
  font-size: medium;
  font-weight: 500;
}

.yellow-btn:active {
  background-color: #f5cc5c;
  /* 点击时略深 */
  border-color: #f4c134;
  color: #fff;
  font-size: medium;
  font-weight: 500;
}

.yellow-btn.is-disabled {
  background-color: #f5f5f5;
  border-color: #f0f0f0;
  color: #aaa;
}

/* 止 disabled 按钮 hover 后变色 */
.yellow-btn.is-disabled,
.yellow-btn.is-disabled:hover {
  background-color: #f5f5f5 !important;
  border-color: #d9d9d9 !important;
  color: #bfbfbf !important;
  cursor: not-allowed;
}

.page-title {
  color: #303133;
  font-size: 24px;
  margin: 0;
}

.content-wrapper {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 卡片样式 */
.card {
  background: #fff;
  /* border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); */
  padding: 20px;
  margin-bottom: 20px;
}

/* 输入区域 */
.input-section {
  display: flex;
  flex-direction: column;
  gap: 15px;
  line-height: 1.5;
}

.action-btn-group {
  display: flex;
  justify-content: flex-end;
}

/* 图表区域 */
.chart-area {
  margin-top: 20px;
}

.section-title {
  color: #303133;
  font-size: 18px;
  margin-top: 0;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.chart-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
  gap: 20px;
}

.chart-item {
  height: 350px;
}

.trend-chart-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 30px;
}

.trend-chart-item {
  height: 400px;
}

/* 诊断结果 */
.diagnosis-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
  line-height: 1.5;
}

.diagnosis-column {
  display: flex;
  flex-direction: column;
}

.advantage-title {
  color: #67C23A;
  margin-bottom: 10px;
}

.issue-title {
  color: #E6A23C;
  margin-bottom: 10px;
}

.advantage-list,
.issue-list {
  padding-left: 20px;
}

.advantage-list li {
  color: #67C23A;
  margin-bottom: 8px;
}

.issue-item {
  color: #E6A23C;
  margin-bottom: 5px;
}

.suggestion-item {
  color: #606266;
  line-height: 1.5;
  padding: 5px;
  /* margin-left: 20px; */
}

/* 综合评估 */
.assessment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.job-fit-section {
  text-align: center;
}

.fit-score {
  display: flex;
  align-items: baseline;
  justify-content: center;
  gap: 10px;
}

.score-value {
  font-size: 48px;
  color: #409EFF;
  font-weight: bold;
}

.score-level {
  font-size: 16px;
  color: #909399;
}

.position-info {
  font-size: 16px;
  color: #606266;
}

.evaluation-content {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.evaluation-text {
  margin: 0;
  line-height: 1.6;
  color: #606266;
}

/* 资源推荐 */
.resource-header {
  margin-bottom: 15px;
}

.suggestion-text {
  color: #606266;
  margin: 10px 0 0;
}

.resource-list {
  padding-left: 0;
  list-style: none;
}

.resource-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px dashed #ebeef5;
}

.resource-text {
  flex: 1;
  color: #606266;
}

/* 分析内容 */
.analysis-content {
  color: #606266;
  line-height: 1.8;
  margin: 0;
}

/* 按钮样式 */
.primary-btn {
  background-color: #409EFF;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
}

.primary-btn:hover {
  background-color: #66b1ff;
}

.resource-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px dashed #ebeef5;
}

.resource-info {
  flex: 1;
}

.resource-name {
  display: block;
  color: #606266;
  font-weight: 500;
}

.resource-type {
  font-size: 12px;
  color: #909399;
}

.resource-actions {
  display: flex;
  gap: 8px;
}

.page-container {
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式调整 */
@media (max-width: 992px) {
  .diagnosis-section {
    grid-template-columns: 1fr;
  }

  .chart-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .header-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .assessment-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .fit-score {
    justify-content: flex-start;
  }
}

.qa-analysis-section {
  margin-bottom: 24px;
}

.qa-block {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 16px 20px;
  margin-bottom: 20px;
  background-color: #fafafa;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
}

/* 每一小节 */
.qa-section {
  margin-bottom: 12px;
  display: flex;
  flex-direction: row;
  align-items: flex-start;
}

/* 左侧标题 */
.qa-title {
  font-weight: 600;
  width: 100px;
  flex-shrink: 0;
  color: #303133;
}

/* 右侧内容自动换行 */
.qa-content {
  flex: 1;
  color: #606266;
  line-height: 1.6;
  word-break: break-word;
}

/* 分类上色 */
.qa-ai-answer .qa-content {
  color: #409EFF;
}

.qa-user-answer .qa-content {
  color: #909399;
}

.qa-advantage .qa-content {
  color: #67C23A;
}

.qa-disadvantage .qa-content {
  color: #E6A23C;
}

.qa-suggestion .qa-content {
  color: #909399;
}
</style>
